package org.charles.zhifou.scoring;


import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.charles.zhifou.common.exception.BusinessException;
import org.charles.zhifou.common.response.ResponseCodeEnum;
import org.charles.zhifou.enums.AppTypeEnum;
import org.charles.zhifou.enums.ScoringStrategyEnum;
import org.charles.zhifou.model.entity.App;
import org.charles.zhifou.model.entity.UserAnswer;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 评分策略执行器
 */
@Service
@Slf4j
public class ScoringStrategyExecutor {

    // 策略列表
    @Resource
    private List<ScoringStrategy> scoringStrategyList;


    /**
     * 评分
     *
     * @param choiceList
     * @param app
     * @return
     * @throws Exception
     */
    public void doScore(UserAnswer userAnswer, App app) throws Exception {
        AppTypeEnum appType = app.getAppType();
        ScoringStrategyEnum scoringStrategy = app.getScoringStrategy();

        // 顺便填入 App 相关参数
        userAnswer.setAppType(app.getAppType());
        userAnswer.setScoringStrategy(app.getScoringStrategy());

        // 根据注解获取策略
        for (ScoringStrategy strategy : scoringStrategyList) {
            if (strategy.getClass().isAnnotationPresent(ScoringStrategyService.class)) {
                ScoringStrategyService scoringStrategyService = strategy.getClass().getAnnotation(ScoringStrategyService.class);
                if (scoringStrategyService.appType().equals(appType) && scoringStrategyService.scoringStrategy().equals(scoringStrategy)) {
                    strategy.doScore(userAnswer, app);
                    return;
                }
            }
        }

        throw new BusinessException(ResponseCodeEnum.SYSTEM_ERROR, "应用配置有误, 未找到匹配的策略");
    }
}
